home *** CD-ROM | disk | FTP | other *** search
/ Internet Surfer 2.0 / Internet Surfer 2.0 (Wayzata Technology) (1996).iso / pc / textfile / faqs / c_faq / abridged next >
Encoding:
Text File  |  1992-12-26  |  30.4 KB  |  964 lines

  1. Xref: bloom-picayune.mit.edu comp.lang.c:62383 news.answers:4599
  2. Newsgroups: comp.lang.c,news.answers
  3. Path: bloom-picayune.mit.edu!adam.mit.edu!scs
  4. From: scs@adam.mit.edu (Steve Summit)
  5. Subject: comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ)
  6. Message-ID: <1992Dec15.160735.21337@athena.mit.edu>
  7. Followup-To: poster
  8. Sender: news@athena.mit.edu (News system)
  9. Supersedes: <1992Dec1.025558.25274@athena.mit.edu>
  10. Nntp-Posting-Host: adam.mit.edu
  11. Reply-To: scs@adam.mit.edu
  12. X-Archive-Name: C-faq/abridged
  13. Organization: none, at the moment
  14. Date: Tue, 15 Dec 1992 16:07:35 GMT
  15. X-Last-Modified: November 3, 1992
  16. Approved: news-answers-request@MIT.Edu
  17. Expires: Wed, 6 Jan 1993 00:00:00 GMT
  18. Lines: 944
  19.  
  20. Archive-name: C-faq/abridged
  21.  
  22. [Last modified November 3, 1992 by scs.]
  23.  
  24. This article contains minimal answers to the comp.lang.c frequently-
  25. asked questions list.  Please see the long version (posted on the
  26. first of each month, or see question 17.21) for more detailed
  27. explanations and references.
  28.  
  29.  
  30. Section 1. Null Pointers
  31.  
  32. 1.1:    What is this infamous null pointer, anyway?
  33.  
  34. A:    For each pointer type, there is a special value -- the "null
  35.     pointer" -- which is distinguishable from all other pointer
  36.     values and which is not the address of any object.
  37.  
  38. 1.2:    How do I "get" a null pointer in my programs?
  39.  
  40. A:    A constant 0 in a pointer context is converted into a null
  41.     pointer at compile time.  A "pointer context" is an
  42.     initialization, assignment, or comparison with one side a
  43.     variable or expression of pointer type, and (in ANSI standard C)
  44.     a function argument which has a prototype in scope declaring a
  45.     certain parameter as being of pointer type.  In other contexts
  46.     (function arguments without prototypes, or in the variable part
  47.     of variadic function calls) a constant 0 with an appropriate
  48.     explicit cast is required.
  49.  
  50. 1.3:    What is NULL and how is it #defined?
  51.  
  52. A:    NULL is simply a preprocessor macro, #defined as 0 (or
  53.     (void *)0), which is used (as a stylistic convention, in
  54.     preference to unadorned 0's) to generate null pointers,
  55.  
  56. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  57.     bit pattern as the internal representation of a null pointer?
  58.  
  59. A:    The same as any other machine: as 0 (or (void *)0).  (The
  60.     compiler makes the translation, upon seeing a 0, not the
  61.     preprocessor.)
  62.  
  63. 1.5:    If NULL were defined as "(char *)0," wouldn't that make function
  64.     calls which pass an uncast NULL work?
  65.  
  66. A:    Not in general.  The problem is that there are machines which
  67.     use different internal representations for pointers to different
  68.     types of data.  A cast is still required to tell the compiler
  69.     which kind of null pointer is required, since it may be
  70.     different from (char *)0.
  71.  
  72. 1.6:    I use the preprocessor macro "#define Nullptr(type) (type *)0"
  73.     to help me build null pointers of the correct type.
  74.  
  75. A:    This trick, though valid, does not buy much.
  76.  
  77. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  78.     null pointers valid?  What if the internal representation for
  79.     null pointers is nonzero?
  80.  
  81. A:    The construction "if(p)" works, regardless of the internal
  82.     representation of null pointers, because the compiler
  83.     essentially rewrites it as "if(p != 0)" and goes on to convert 0
  84.     into the correct null pointer.
  85.  
  86. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  87.  
  88. A:    Either; the distinction is entirely stylistic.
  89.  
  90. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  91.     the value of NULL changes, perhaps on a machine with nonzero
  92.     null pointers?
  93.  
  94. A:    No.  NULL is, and will always be, 0.
  95.  
  96. 1.10:    I'm confused.  NULL is guaranteed to be 0, but the null pointer
  97.     is not?
  98.  
  99. A:    A "null pointer" is a language concept whose particular internal
  100.     value does not matter.  A null pointer is requested in source
  101.     code with the character "0".  "NULL" is a preprocessor macro,
  102.     which is always #defined as 0 (or (void *)0).
  103.  
  104. 1.11:    Why is there so much confusion surrounding null pointers?  Why
  105.     do these questions come up so often?
  106.  
  107. A:    The fact that null pointers are represented both in source code,
  108.     and internally to most machines, as zero invites unwarranted
  109.     assumptions.  The use of a preprocessor macro (NULL) suggests
  110.     that the value might change later, or on some weird machine.
  111.  
  112. 1.12:    I'm still confused.  I just can't understand all this null
  113.     pointer stuff.
  114.  
  115. A:    A simple rule is, "Always use `0' or `NULL' for null pointers,
  116.     and always cast them when they are used as arguments in function
  117.     calls."
  118.  
  119. 1.13:    Given all the confusion surrounding null pointers, wouldn't it
  120.     be easier simply to require them to be represented internally by
  121.     zeroes?
  122.  
  123. A:    Such a requirement would accomplish little.
  124.  
  125. 1.14:    Seriously, have any actual machines really used nonzero null
  126.     pointers?
  127.  
  128. A:    Machines manufactured by Prime and by Honeywell-Bull, as well as
  129.     Symbolics Lisp Machines, have done so.
  130.  
  131.  
  132. Section 2. Arrays and Pointers
  133.  
  134. 2.1:    I had the definition char a[6] in one source file, and in
  135.     another I declared extern char *a.  Why didn't it work?
  136.  
  137. A:    The declaration extern char *a simply does not match the actual
  138.     definition.  Use extern char a[].
  139.  
  140. 2.2:    But I heard that char a[] was identical to char *a.
  141.  
  142. A:    Not at all.  Arrays are not pointers.  A reference like x[3]
  143.     generates different code depending on whether x is an array or a
  144.     pointer.
  145.  
  146. 2.3:    So what is meant by the "equivalence of pointers and arrays"
  147.     in C?
  148.  
  149. A:    An lvalue of type array-of-T which appears in an expression
  150.     decays into a pointer to its first element; the type of the
  151.     resultant pointer is pointer-to-T.  So for an array a and
  152.     pointer p, you can say "p = a;" and then p[3] and a[3] will
  153.     access the same element.
  154.  
  155. 2.4:    Why are array and pointer declarations interchangeable as
  156.     function formal parameters?
  157.  
  158. A:    Since functions can never receive arrays as parameters, any
  159.     parameter declarations which "look like" arrays are treated by
  160.     the compiler as if they were pointers.
  161.  
  162. 2.5:    Why doesn't sizeof properly report the size of an array which is
  163.     a parameter to a function?
  164.  
  165. A:    The sizeof operator reports the size of the pointer parameter
  166.     which the function actually receives.
  167.  
  168. 2.6:    Someone explained to me that arrays were really just constant
  169.     pointers.
  170.  
  171. A:    An array name is "constant" in that it cannot be assigned to,
  172.     but an array is _not_ a pointer.
  173.  
  174. 2.7:    I came across some "joke" code containing the "expression"
  175.     5["abcdef"] .  How can this be legal C?
  176.  
  177. A:    Yes, array subscripting is commutative in C.  The array
  178.     subscripting operation a[e] is defined as being equivalent to
  179.     *((a)+(e)).
  180.  
  181. 2.8:    My compiler complained when I passed a two-dimensional array to
  182.     a routine expecting a pointer to a pointer.
  183.  
  184. A:    The rule by which arrays decay into pointers is not applied
  185.     recursively.  An array of arrays (i.e. a two-dimensional array
  186.     in C) decays into a pointer to an array, not a pointer to a
  187.     pointer.
  188.  
  189. 2.9:    How do I declare a pointer to an array?
  190.  
  191. A:    Usually, you don't want to.  Consider using a pointer to one of
  192.     the array's elements instead.
  193.  
  194. 2.10:    How can I dynamically allocate a multidimensional array?
  195.  
  196. A:    It is usually best to allocate an array of pointers, and then
  197.     initialize each pointer to a dynamically-allocated "row."
  198.     See the full list for code samples.
  199.  
  200. 2.11:    Can I simulate a non-0-based array with a pointer?
  201.  
  202. A:    Not if the pointer points outside of the block of memory it is
  203.     intended to access.
  204.  
  205. 2.12:    I passed a pointer to a function which initialized it, but the
  206.     pointer in the caller was unchanged.
  207.  
  208. A:    The called function probably altered only the passed copy of the
  209.     pointer.
  210.  
  211. 2.13:    I have a char * pointer that happens to point to some ints, and
  212.     I want to step it over them.  Why doesn't "((int *)p)++;" work?
  213.  
  214. A:    In C, a cast operator is a conversion operator, and by
  215.     definition it yields an rvalue, which cannot be assigned to, or
  216.     incremented with ++.
  217.  
  218.  
  219. Section 3. Memory Allocation
  220.  
  221. 3.1:    Why doesn't the code "char *answer; gets(answer);" work?
  222.  
  223. A:    The pointer variable "answer" has not been set to point to any
  224.     valid storage.  The simplest way to correct this fragment is to
  225.     use a local array, instead of a pointer.
  226.  
  227. 3.2:    I can't get strcat to work.  I tried "char *s1 = "Hello, ",
  228.     *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange
  229.     results.
  230.  
  231. A:    Again, the problem is that space for the concatenated result is
  232.     not properly allocated.
  233.  
  234. 3.3:    But the man page for strcat says that it takes two char *'s as
  235.     arguments.  How am I supposed to know to allocate things?
  236.  
  237. A:    In general, when using pointers you _always_ have to consider
  238.     memory allocation, at least to make sure that the compiler is
  239.     doing it for you.
  240.  
  241. 3.4:    I have a function that is supposed to return a string, but when
  242.     it returns to its caller, the returned string is garbage.
  243.  
  244. A:    Make sure that the memory to which the function returns a
  245.     pointer is correctly (i.e. not locally) allocated.
  246.  
  247. 3.5:    You can't use dynamically-allocated memory after you free it,
  248.     can you?
  249.  
  250. A:    No.  Some early man pages implied otherwise, but the claim is no
  251.     longer valid.
  252.  
  253. 3.6:    How does free() know how many bytes to free?
  254.  
  255. A:    The malloc/free package remembers the size of each block it
  256.     allocates and returns.
  257.  
  258. 3.7:    So can I query the malloc package to find out how big an
  259.     allocated block is?
  260.  
  261. A:    Not portably.
  262.  
  263. 3.8:    Is it legal to pass a null pointer as the first argument to
  264.     realloc()?
  265.  
  266. A:    ANSI C sanctions this usage, but several earlier implementations
  267.     do not support it.
  268.  
  269. 3.9:    Is it safe to use calloc's zero-fill guarantee for pointer and
  270.     floating-point values?
  271.  
  272. A:    No.
  273.  
  274. 3.10:    What is alloca and why is its use discouraged?
  275.  
  276. A:    alloca allocates memory which is automatically freed when the
  277.     function which called alloca returns.  alloca cannot be written
  278.     portably, is difficult to implement on machines without a stack,
  279.     and fails under certain conditions if implemented simply.
  280.  
  281.  
  282. Section 4. Expressions
  283.  
  284. 4.1:    Why doesn't the code "a[i] = i++;" work?
  285.  
  286. A:    The variable i is both referenced and modified in the same
  287.     expression.
  288.  
  289. 4.2:    Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++);"
  290.     prints 49.  Regardless of the order of evaluation, shouldn't it
  291.     print 56?
  292.  
  293. A:    The operations implied by the postincrement and postdecrement
  294.     operators ++ and -- are performed at some time after the
  295.     operand's former values are yielded and before the end of the
  296.     expression, but not necessarily immediately after, or before
  297.     other parts of the expression are evaluated.
  298.  
  299. 4.3:    But what about the &&, ||, and comma operators?
  300.  
  301. A:    There is a special exception for those operators, (as well
  302.     as ?: ); left-to-right evaluation is guaranteed.
  303.  
  304. 4.4:    If I'm not using the value of the expression, should I use i++
  305.     or ++i to increment a variable?
  306.  
  307. A:    Since the two forms differ only in the value yielded, they are
  308.     entirely equivalent when only their side effect is needed.
  309.  
  310. 4.5:    Why doesn't the code "int a = 1000, b = 1000;
  311.     long int c = a * b;" work?
  312.  
  313. A:    You must manually cast one of the operands to (long).
  314.  
  315.  
  316. Section 5. ANSI C
  317.  
  318. 5.1:    What is the "ANSI C Standard?"
  319.  
  320. A:    In 1983, the American National Standards Institute commissioned
  321.     a committee, X3J11, to standardize the C language.  After a
  322.     long, arduous process, the committee's work was finally ratified
  323.     as an American National Standard, X3.159-1989, on December 14,
  324.     1989, and published in the spring of 1990.  The Standard has
  325.     also been adopted as ISO/IEC 9899:1990.
  326.  
  327. 5.2:    How can I get a copy of the Standard?
  328.  
  329. A:    Copies are available from the American National Standards
  330.     Institute in New York, or from Global Engineering Documents in
  331.     Irvine, CA.  See the unabridged list for addresses.
  332.  
  333. 5.3:    Does anyone have a tool for converting old-style C programs to
  334.     ANSI C, or for automatically generating prototypes?
  335.  
  336. A:    See the full list for details.
  337.  
  338. 5.4:    How do I keep the ANSI "stringizing" preprocessing operator from
  339.     stringizing the macro's name rather than its value?
  340.  
  341. A:    You must use a two-step #definition to force the macro to be
  342.     expanded as well as stringized.
  343.  
  344. 5.5:    What's the difference between "char const *p" and
  345.     "char * const p"?
  346.  
  347. A:    The former is a pointer to a constant character; the latter is a
  348.     constant pointer to a character.
  349.  
  350. 5.6:    My ANSI compiler complains about a mismatch when it sees
  351.  
  352.         extern int func(float);
  353.  
  354.         int func(x)
  355.         float x;
  356.         {...
  357.  
  358. A:    You have mixed the new-style prototype declaration
  359.     "extern int func(float);" with the old-style definition
  360.     "int func(x) float x;".  "Narrow" types are treated differently
  361.     according to which syntax is used.  The problem can be fixed by
  362.     using either new-style (prototype) or old-style syntax
  363.     consistently.
  364.  
  365. 5.7:    I'm getting strange syntax errors inside code which I've
  366.     #ifdeffed out.
  367.  
  368. A:    Under ANSI C, #ifdeffed-out text must still consist of "valid
  369.     preprocessing tokens."  This means that there must be no
  370.     unterminated comments or quotes (i.e. no single apostrophes),
  371.     and no newlines inside quotes.
  372.  
  373. 5.8:    Can I declare main as void, to shut off these annoying "main
  374.     returns no value" messages?
  375.  
  376. A:    No.
  377.  
  378. 5.9:    Why does the ANSI Standard not guarantee more than six monocase
  379.     characters of external identifier significance?
  380.  
  381. A:    The problem is older linkers which cannot be forced (by mere
  382.     words in a Standard) to upgrade.
  383.  
  384. 5.10:    What is the difference between memcpy and memmove?
  385.  
  386. A:    memmove offers guaranteed behavior if the source and destination
  387.     arguments overlap.
  388.  
  389. 5.11:    My compiler is rejecting the simplest possible test programs,
  390.     with all kinds of syntax errors.
  391.  
  392. A:    Perhaps it is a pre-ANSI compiler.
  393.  
  394. 5.12:    Why won't frobozz-cc, which claims to be ANSI compliant, accept
  395.     this code?
  396.  
  397. A:    Are you sure that the code being rejected doesn't rely on some
  398.     non-Standard extension?
  399.  
  400. 5.13:    What are #pragmas and what are they good for?
  401.  
  402. A:    The #pragma directive provides a single, well-defined "escape
  403.     hatch" which can be used for extensions.
  404.  
  405.  
  406. Section 6. C Preprocessor
  407.  
  408. 6.1:    How can I write a generic macro to swap two values?
  409.  
  410. A:    There is no good answer to this question.  The best all-around
  411.     solution is probably to forget about using a macro.
  412.  
  413. 6.2:    I have some old code that tries to construct identifiers with a
  414.     macro like "#define Paste(a, b) a/**/b ", but it doesn't work
  415.     any more.
  416.  
  417. A:    Try the ANSI token-pasting operator ##.
  418.  
  419. 6.3:    What's the best way to write a multi-statement cpp macro?
  420.  
  421. A:    #define Func() do {stmt1; stmt2; ... } while(0)  /* (no trailing ;) */
  422.  
  423. 6.4:    Is it acceptable for one header file to #include another?
  424.  
  425. A:    There has been considerable debate surrounding this question.
  426.  
  427. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  428.  
  429. A:    No.
  430.  
  431. 6.6:    How can I use a preprocessor #if expression to detect
  432.     endianness?
  433.  
  434. A:    You probably can't.
  435.  
  436. 6.7:    I've got this tricky processing I want to do at compile time and
  437.     I can't figure out a way to get cpp to do it.
  438.  
  439. A:    Consider writing your own little special-purpose preprocessing
  440.     tool, instead.
  441.  
  442. 6.8:    How can I write a cpp macro which takes a variable number of
  443.     arguments?
  444.  
  445. A:    Here is one popular trick.  Note that the parentheses around
  446.     printf's argument list are in the macro call, not the
  447.     definition.
  448.  
  449.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  450.  
  451.         if(n != 0) DEBUG(("n is %d\n", n));
  452.  
  453.  
  454. Section 7. Variable-Length Argument Lists
  455.  
  456. 7.1:    How can I write a function that takes a variable number of
  457.     arguments?
  458.  
  459. A:    Use the <stdarg.h> (or older <varargs.h>) header.
  460.  
  461. 7.2:    How can I write a function that takes a format string and a
  462.     variable number of arguments, like printf, and passes them to
  463.     printf to do most of the work?
  464.  
  465. A:    Use vprintf, vfprintf, or vsprintf.
  466.  
  467. 7.3:    How can I discover how many arguments a function was actually
  468.     called with?
  469.  
  470. A:    Any function which takes a variable number of arguments must be
  471.     able to determine from the arguments themselves how many of them
  472.     there are.
  473.  
  474. 7.4:    How can I write a function which takes a variable number of
  475.     arguments and passes them to some other function (which takes a
  476.     variable number of arguments)?
  477.  
  478. A:    In general, you cannot.
  479.  
  480. 7.5:    How can I call a function with an argument list built up at run
  481.     time?
  482.  
  483. A:    You can't.
  484.  
  485.  
  486. Section 8. Boolean Expressions and Variables
  487.  
  488. 8.1:    What is the right type to use for boolean values in C?  Why
  489.     isn't it a standard type?  Should #defines or enums be used for
  490.     the true and false values?
  491.  
  492. A:    C does not provide a standard boolean type, because picking one
  493.     involves a space/time tradeoff which is best decided by the
  494.     programmer.  The choice between #defines and enums is arbitrary
  495.     and not terribly interesting.
  496.  
  497. 8.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  498.     is considered "true" in C?  What if a built-in boolean or
  499.     relational operator "returns" something other than 1?
  500.  
  501. A:    It is true (sic) that any nonzero value is considered true in C,
  502.     but this applies only "on input", i.e. where a boolean value is
  503.     expected.  When a boolean value is generated by a built-in
  504.     operator, it is guaranteed to be 1 or 0.  (This is _not_ true
  505.     for some library routines such as isalpha.)
  506.  
  507.  
  508. Section 9. Structs, Enums, and Unions
  509.  
  510. 9.1:    What is the difference between an enum and a series of
  511.     preprocessor #defines?
  512.  
  513. A:    At the present time, there is little difference.  The ANSI
  514.     standard states that enumerations are compatible with integral
  515.     types.
  516.  
  517. 9.2:    I heard that structures could be assigned to variables and
  518.     passed to and from functions, but K&R I says not.
  519.  
  520. A:    These operations are supported by all modern compilers.
  521.  
  522. 9.3:    How does struct passing and returning work?
  523.  
  524. A:    If you really need to know, see the unabridged list.
  525.  
  526. 9.4:    I have a program which works correctly, but dumps core after it
  527.     finishes.  Why?
  528.  
  529. A:    Check to see if a structure type declaration just before main is
  530.     missing its trailing semicolon, causing the compiler to believe
  531.     that main returns a structure.  See also question 17.15.
  532.  
  533. 9.5:    Why can't you compare structs?
  534.  
  535. A:    There is no reasonable way for a compiler to implement struct
  536.     comparison which is consistent with C's low-level flavor.
  537.  
  538. 9.6:    I came across some code that declared a structure with the last
  539.     member an array of one element, and then did some tricky
  540.     allocation to make the array act like it had several elements.
  541.     Is this legal and/or portable?
  542.  
  543. A:    The ANSI C standard allows it, but only implicitly.
  544.  
  545. 9.7:    How can I determine the byte offset of a field within a
  546.     structure?
  547.  
  548. A:    ANSI C defines the offsetof macro, which should be used if
  549.     available.
  550.  
  551. 9.8:    How can I access structure fields by name at run time?
  552.  
  553. A:    Build a table of names and offsets, using the offsetof() macro.
  554.  
  555. 9.9:    Why does sizeof report a larger size than I expect for a
  556.     structure type, as if there was padding at the end?
  557.  
  558. A:    The alignment of arrays of structures must be preserved.
  559.  
  560. 9.10:    How can I turn off structure padding?
  561.  
  562. A:    There is no standard method.
  563.  
  564. 9.11:    Can I initialize unions?
  565.  
  566. A:    ANSI Standard C allows an initializer for the first member.
  567.  
  568.  
  569. Section 10. Declarations
  570.  
  571. 10.1:    How do you decide which integer type to use?
  572.  
  573. A:    If you might need large values, use long.  Otherwise, if space
  574.     is very important, use short.  Otherwise, use int.
  575.  
  576. 10.2:    I can't seem to define a linked list node which contains a
  577.     pointer to itself.
  578.  
  579. A:    Structs in C can certainly contain pointers to themselves; the
  580.     discussion and example in section 6.5 of K&R make this clear.
  581.     Problems arise if an attempt is made to define (and use) a
  582.     typedef in the midst of such a declaration; avoid this.
  583.  
  584. 10.3:    How do I declare an array of pointers to functions returning
  585.     pointers to functions returning pointers to characters?
  586.  
  587. A:    char *(*(*a[5])())();
  588.     Using a chain of typedefs, or the cdecl program, makes these
  589.     declarations easier.
  590.  
  591. 10.4:    How can I declare a function that returns a pointer to a
  592.     function of its own type?
  593.  
  594. A:    You can't do it directly.
  595.  
  596. 10.5:    What's the best way to declare and define global variables?
  597.  
  598. A:    It is best to place the definition in some central .c file, with
  599.     an external declaration in a header file.
  600.  
  601. 10.6:    How do I initialize a pointer to a function?
  602.  
  603. A:    Use something like "extern int func(); int (*fp)() = func;" .
  604.  
  605. 10.7:    I've seen different methods used for calling through pointers to
  606.     functions.
  607.  
  608. A:    The extra parentheses and explicit * are now officially
  609.     optional, although some older implementations require them.
  610.  
  611.  
  612. Section 11. Stdio
  613.  
  614. 11.1:    Why doesn't the code "char c; while((c = getchar()) != EOF)..."
  615.     work?
  616.  
  617. A:    The variable to hold getchar's return value must be an int.
  618.  
  619. 11.2:    Why does errno contain ENOTTY after a call to printf?
  620.  
  621. A:    Don't worry about it.  It is only meaningful for a program to
  622.     inspect the contents of errno after an error has occurred.
  623.  
  624. 11.3:    My program's prompts and intermediate output don't always show
  625.     up on the screen, especially when I pipe the output through
  626.     another program.
  627.  
  628. A:    It is best to use an explicit fflush(stdout) whenever output
  629.     should definitely be visible.
  630.  
  631. 11.4:    When I read from the keyboard with scanf, it seems to hang until
  632.     I type one extra line of input.
  633.  
  634. A:    scanf was designed for free-format input, which is seldom what
  635.     you want when reading from the keyboard.
  636.  
  637. 11.5:    Will fflush(stdin) flush unread characters from the standard
  638.     input stream?
  639.  
  640. A:    No.
  641.  
  642. 11.6:    Once I've used freopen, how can I get the original stdout back?
  643.  
  644. A:    It's not easy.  Try avoiding freopen.
  645.  
  646. 11.7:    How can I recover the file name given an open file descriptor?
  647.  
  648. A:    This problem is, in general, insoluble.  It is best to remember
  649.     the names of files yourself when you open them.
  650.  
  651.  
  652. Section 12. Library Subroutines
  653.  
  654. 12.1:    I'm trying to sort an array of strings with qsort, using strcmp
  655.     as the comparison function, but it's not working.
  656.  
  657. A:    You'll have to write a "helper" comparison function which takes
  658.     two generic pointer arguments, converts them to char **, and
  659.     dereferences them, yielding char *'s which can be usefully
  660.     compared.
  661.  
  662. 12.2:    Now I'm trying to sort an array of structures with qsort.  My
  663.     comparison routine takes pointers to structures, but the
  664.     compiler complains that the function is of the wrong type for
  665.     qsort.  How can I cast the function pointer to shut off the
  666.     warning?
  667.  
  668. A:    The conversions must be in the comparison function, which must
  669.     be declared as accepting "generic pointers" (void * or char *).
  670.  
  671. 12.3:    How can I convert numbers to strings?
  672.  
  673. A:    Just use sprintf.
  674.  
  675. 12.4:    How can I get the time of day in a C program?
  676.  
  677. A:    Just use the time, ctime, and/or localtime functions.
  678.  
  679. 12.5:    How can I convert a struct tm or a string into a time_t?
  680.  
  681. A:    The ANSI mktime routine converts a struct tm to a time_t.
  682.     No standard routine exists to parse strings.
  683.  
  684. 12.6:    I need a random number generator.
  685.  
  686. A:    The standard C library has one: rand().
  687.  
  688. 12.7:    Each time I run my program, I get the same sequence of random
  689.     numbers.
  690.  
  691. A:    You can call srand() to seed the pseudo-random number generator
  692.     with a more random initial value.
  693.  
  694. 12.8:    I need a random true/false value, so I'm taking rand() % 2, but
  695.     it's just alternating 0, 1, 0, 1, 0...
  696.  
  697. A:    Try using the higher-order bits.
  698.  
  699. 12.9-13: I'm trying to port this old program.  Why do I get "undefined
  700.     external" errors for some library routines?
  701.  
  702. A:    Some semistandard routines have been renamed or replaced over
  703.     the years; see the full list for details.
  704.  
  705. 12.14:    How can I execute a command with system() and read its output
  706.     into a program?
  707.  
  708. A:    Unix and some other systems provide a popen() routine.
  709.  
  710. 12.15:    How can I read a directory in a C program?
  711.  
  712. A:    See if you can use the opendir() and readdir() routines.
  713.  
  714.  
  715. Section 13. Lint
  716.  
  717. 13.1:    I just typed in this program, and it's acting strangely.
  718.     Can you see anything wrong with it?
  719.  
  720. A:    Try running lint first.
  721.  
  722. 13.2:    How can I shut off the "warning: possible pointer alignment
  723.     problem" message lint gives me for each call to malloc?
  724.  
  725. A:    It may be easier simply to ignore the message, perhaps in an
  726.     automated way with grep -v.
  727.  
  728. 13.3:    Where can I get an ANSI-compatible lint?
  729.  
  730. A:    See the unabridged list for two commercial products.
  731.  
  732.  
  733. Section 14. Style
  734.  
  735. 14.1:    Is the code "if(!strcmp(s1, s2))" good style?
  736.  
  737. A:    Perhaps; perhaps not.
  738.  
  739. 14.2:    What's the best style for code layout in C?
  740.  
  741. A:    There is no one "best style," but see the full list for a few
  742.     suggestions.
  743.  
  744. 14.3:    Where can I get the "Indian Hill Style Guide" and other coding
  745.     standards?
  746.  
  747. A:    See the unabridged list.
  748.  
  749.  
  750. Section 15. Floating Point
  751.  
  752. 15.1:    My floating-point calculations are acting strangely and giving
  753.     me different answers on different machines.
  754.  
  755. A:    First, make sure that you have #included <math.h>, and correctly
  756.     declared other functions returning double.  If the problem isn't
  757.     that simple, see the full list for a brief explanation, or any
  758.     good programming book for a better one.
  759.  
  760. 15.2:    I keep getting "undefined: _sin" compilation errors.
  761.  
  762. A:    Make sure you're linking against the correct math library.
  763.  
  764. 15.3:    Why doesn't C have an exponentiation operator?
  765.  
  766. A:    Try using the pow() function.
  767.  
  768. 15.4:    I'm having trouble with a Turbo C program which crashes and says
  769.     something like "floating point formats not linked."
  770.  
  771. A:    Some compilers for small machines, including Turbo C, attempt to
  772.     leave out floating point support if it looks like it will not be
  773.     needed.  The programmer must occasionally insert a dummy
  774.     explicit floating-point call to force loading of floating-point
  775.     support.
  776.  
  777.  
  778. Section 16. System Dependencies
  779.  
  780. 16.1:    How can I read a single character from the keyboard without
  781.     waiting for a newline?
  782.  
  783. A:    Contrary to popular belief and many people's wishes, this is not
  784.     a C-related question.  How to do so is a function of the
  785.     operating system in use.
  786.  
  787. 16.2:    How can I find out if there are characters available for reading
  788.     (and if so, how many)?  Alternatively, how can I do a read that
  789.     will not block if there are no characters available?
  790.  
  791. A:    These, too, are entirely operating-system-specific.
  792.  
  793. 16.3:    How can I clear the screen?
  794.  
  795. A:    Such things depend on the output device you're using.
  796.  
  797. 16.4:    How do I read the mouse?
  798.  
  799. A:    What system are you using?
  800.  
  801. 16.5:    How can my program discover the complete pathname to the
  802.     executable file from which it was invoked?
  803.  
  804. A:    argv[0] may contain all or part of the pathname.  You may be
  805.     able to duplicate the command language interpreter's search path
  806.     logic to locate the executable.
  807.  
  808. 16.6:    How can a process change an environment variable in its caller?
  809.  
  810. A:    In general, it cannot.
  811.  
  812. 16.7:    How can I find out the size of a file, prior to reading it in?
  813.  
  814. A:    You might be able to get an estimate using stat() or
  815.     fseek/ftell.
  816.  
  817. 16.8:    How can a file be shortened in-place without completely clearing
  818.     or rewriting it?
  819.  
  820. A:    There are various ways to do this, but there is no truly
  821.     portable solution.
  822.  
  823. 16.9:    How can I implement a delay, or time a user's response, with
  824.     sub-second resolution?
  825.  
  826. A:    Unfortunately, there is no portable way.
  827.  
  828. 16.10:    How can I read in an object file and jump to routines in it?
  829.  
  830. A:    You want a dynamic linker and/or loader.
  831.  
  832.  
  833. Section 17. Miscellaneous
  834.  
  835. 17.1:    What can I safely assume about the initial values of variables
  836.     which are not explicitly initialized?
  837.  
  838. A:    Variables with "static" duration start out as 0, as if the
  839.     programmer had initialized them.  Variables with "automatic"
  840.     duration, and dynamically-allocated memory, start out containing
  841.     garbage (with the exception of calloc).
  842.  
  843. 17.2:    How can I write data files which can be read on other machines
  844.     with different data formats?
  845.  
  846. A:    The best solution is to use text files.
  847.  
  848. 17.3:    How can I return several values from a function?
  849.  
  850. A:    Either pass pointers to locations which the function can fill
  851.     in, or have the function return a structure containing the
  852.     desired values.
  853.  
  854. 17.4:    How can I call a function, given its name as a string?
  855.  
  856. A:    The most straightforward thing to do is maintain a
  857.     correspondence table of names and function pointers.
  858.  
  859. 17.5:    I seem to be missing the system header file <sgtty.h>.
  860.     Can someone send me a copy?
  861.  
  862. A:    You cannot just pick up a copy of someone else's header file and
  863.     expect it to work, since the definitions within header files are
  864.     frequently system-dependent.  Contact your vendor.
  865.  
  866. 17.6:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  867.     from C?
  868.  
  869. A:    The answer is entirely dependent on the machine and the specific
  870.     calling sequences of the various compilers in use.
  871.  
  872. 17.7:    Does anyone know of a program for converting Pascal or FORTRAN
  873.     to C?
  874.  
  875. A:    Several public-domain programs are available, namely ptoc, p2c,
  876.     and f2c.  See the full list for details.
  877.  
  878. 17.8:    Where can I get copies of all these public-domain programs?
  879.  
  880. A:    See the regular postings in the comp.sources.unix and
  881.     comp.sources.misc newsgroups for information.
  882.  
  883. 17.9:    When will the next Obfuscated C Code Contest be held
  884.     How can I get a copy of the previous winning entries?
  885.  
  886. A:    See the full list, or send e-mail to obfuscate@toad.com .
  887.  
  888. 17.10:    Why don't C comments nest?  Are they legal inside quoted
  889.     strings?
  890.  
  891. A:    Nested comments would cause more harm than good.  The character
  892.     sequences /* and */ are not special within double-quoted
  893.     strings.
  894.  
  895. 17.11:    How can I implement sets and/or arrays of bits?
  896.  
  897. A:    Use arrays of char or int, with a few macros to access the right
  898.     bit at the right index.
  899.  
  900. 17.12:    What is the most efficient way to count the number of bits which
  901.     are set in a value?
  902.  
  903. A:    This and many other similar bit-twiddling problems can often be
  904.     sped up and streamlined using lookup tables.
  905.  
  906. 17.13:    How can I make this code more efficient?
  907.  
  908. A:    Efficiency is not important nearly as often as people tend to
  909.     think it is.  Most of the time, by simply paying attention to
  910.     good algorithm choices, perfectly acceptable results can be
  911.     achieved.
  912.  
  913. 17.14:    Are pointers really faster than arrays?  How much do function
  914.     calls slow things down?
  915.  
  916. A:    Precise answers to these and many similar questions depend of
  917.     course on the processor and compiler in use.
  918.  
  919. 17.15:    This program crashes before it even runs!
  920.  
  921. A:    Look for very large, local arrays.
  922.     (See also question 9.4.)
  923.  
  924. 17.16:    What does "Segmentation violation" mean?
  925.  
  926. A:    It generally means that your program tried to access memory it
  927.     shouldn't have.
  928.  
  929. 17.17:    Does anyone have a C compiler test suite I can use?
  930.  
  931. A:    Plum Hall, among others, sells one.
  932.  
  933. 17.18:    Where can I get a YACC grammar for C?
  934.  
  935. A:    See the ANSI Standard, or the unabridged list.
  936.  
  937. 17.19:    How do you pronounce "char"?
  938.  
  939. A:    Like the English words "char," "care," or "car" (your choice).
  940.  
  941. 17.20:    What's a good book for learning C?
  942.  
  943. A:    There are far too many to list here; the full list contains a
  944.     few pointers.
  945.  
  946. 17.21:    Where can I get extra copies of this list?
  947.  
  948. A:    For now, just pull it off the net; the unabridged version is
  949.     normally posted on the first of each month, with an Expiration:
  950.     line which should keep it around all month.  It can also be
  951.     found in the newsgroup news.answers .  Several sites archive
  952.     news.answers postings and other FAQ lists, including this one;
  953.     the archie server should help you find them.
  954.  
  955.  
  956.                     Steve Summit
  957.                     scs@adam.mit.edu
  958.                     scs%adam.mit.edu@mit.edu
  959.                     mit-eddie!adam.mit.edu!scs
  960.  
  961. This article is Copyright 1988, 1990-1992 by Steve Summit.
  962. It may be freely redistributed so long as the author's name, and this
  963. notice, are retained.
  964.